// pages/study/study.js
const app = getApp()
var util = require("../../utils/utils.js");
var WxParse = require("../../wxParse/wxParse.js");
Page({
  data: {
    //轮播图配置
    activityId: null,
    courseImg: null,
    fromSwitch: false,
    display: '',
    isShowAllChild: false,
    scrollTop: 1, //初始化滑动高度
    tinscroll: "",
    isBindChild: true,
    showModalStatus: false,
    childRelation: '',
    relation: [],
    relation_index: 0,

  },

  // // 遮罩层隐藏
  applayVideo: function(e) {
    let index = e.currentTarget.dataset.index;
    let src = e.currentTarget.dataset.src;
    let url = e.currentTarget.dataset.url;
    let list = this.data.videolist;
    list.forEach(n => {
      n.isPlaying = false;
    })
    list[index].isPlaying = true;
    list[index].clicks = list[index].clicks + 1;
    this.setData({
      videolist: list
    })
    let videoContext = wx.createVideoContext('video-' + index)
    videoContext.play()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let that = this;
    let types = wx.getStorageSync("type");
    if (!types) {
      types = 0;
    }
    this.setData({
      relation_index: 0,
      types: types,
      show: true, //是否显示观察图片的长度
      activityId: options.activeId, //跳转后带的活动id
      childId: options.childId ? options.childId : '' //跳转后带的孩子ID
    }, () => {
      console.log(that.data.activityId)
      that.queryHeadBanner();
    })
    wx.removeStorageSync("type")
    that.gettops()
  },
  gettops: function() {
    let that = this;
    console.log(that.data.isBindChild)
    //获取学生信息的高度
    setTimeout(function() {
      const query = wx.createSelectorQuery()
      query.select('#plan').boundingClientRect()
      query.select('#parends').boundingClientRect()
      query.select('#photo').boundingClientRect()
      if (that.data.isBindChild) {
        query.select('#sutdyMsg').boundingClientRect()
      } else {
        query.select('#sutdyMsgs').boundingClientRect()
      }
      query.select('#video').boundingClientRect()
      query.select('#pic').boundingClientRect()
      query.exec(function(res) {
        that.setData({
          plan: res[0].top - 34,
          parends: res[1].top - 20,
          photo: res[2].top - 20,
          sutdyMsg: res[3].top - 20,
          video: res[4].top - 20,
          pic: res[5].top - 24,
        })
      })
      wx.hideLoading()
    }, 2000)
  },
  /**
   * 点击滚动相对应高度
   */
  srcoll_jump: function(e) {
    this.setData({
      tinscroll: e.currentTarget.dataset.top
    })
  },
  onShow: function() {
    if (!app.isLogin()) {
      this.getUserInfo();
      return;
    }
    this.initPage();
  },
  initPage: function() {
    let that = this;
    this.setData({
      activityId: app.globalData.activityId ? app.globalData.activityId : that.data.activityId,
      childId: app.globalData.childId ? app.globalData.childId : that.data.childId,
      relation: [{
        value: "0",
        name: "请选择"
      },
      {
        value: "1",
        name: '爸爸'
      },
      {
        value: "2",
        name: '妈妈'
      },
      {
        value: "3",
        name: '亲戚'
      },
      {
        value: "4",
        name: '朋友'
      }
      ],
    });
    this.queryLatelyActivity();
  },
  onChangeShowState: function() {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  getUserInfo: function() {
    let that = this;
    if (app.globalData.appUser != null) {
      return;
    }
    wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.httpUrl + '/common/getUserInfo',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            method: "POST",
            success: function(res) {
              if (res.data.code == '000') {
                app.globalData.appUser = res.data.data;
                app.globalData.openid = res.data.data.openid;
                that.initPage();
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  /**
   * 切换show的值改变是否展示头部长图
   */
  show: function() {
    let that = this;
    that.setData({
      show: !that.data.show
    })
  },
  /**
   * 滑动
   */
  scroll: function(e) {
    this.setData({
      scrollTop: e.detail.scrollTop
    })
  },
  queryLatelyActivity: function() {
    var that = this;
    var params = '';
    if (that.data.activityId) {
      params = '?activityId=' + that.data.activityId;
    }
    if (that.data.childId && that.data.childId != 'undefined') {
      params += params.length > 0 ? "&" : "?";
      if (that.data.childId) {
        params += "childId=" + that.data.childId;
      }
    }
    that.setData({childId: null});
    console.log(params)
    // 小孩最近参加的活动
    wx.request({
      url: app.httpUrl + '/activity/queryLatelyActivity' + params,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        if (res.data.code == '000') {
          if (res.data.data == null) {
            that.setData({
              isBindChild: false
            })
            this.queryActivityInfo(that.data.activityId ? that.data.activityId : null);
            return;
          }
          that.setData({
            isBindChild: true
          })
          this.loadData(res.data.data);
        }
      }
    })
  },
  loadData: function(Activity) {
    var that = this;
    var currTime = new Date().getTime();
    let percent = 0;
    if (Activity.endDate <= currTime) {
      percent = 100;
    } else if (currTime > Activity.startDate) {
      var totalDay = parseInt(Math.ceil((Activity.endDate - Activity.startDate) / 1000 / 60 / 60 / 24));
      var ingDay = parseInt(Math.ceil((currTime - Activity.startDate) / 1000 / 60 / 60 / 24));
      percent = parseInt((ingDay / totalDay) * 100);
    }
    app.globalData.activityId = Activity.activityId;
    that.setData({
      hadData: true,
      percent: percent,
      Activity: Activity,
      ChildActInfo: null
    })
    //课程图组
    this.queryCourseImgList(Activity.courseId);
    if (that.data.isBindChild) {
      //小孩参与活动信息
      this.queryChildActInfo(Activity.activityId, Activity.childId);
      //队伍成员列表
      this.queryMarineMember(Activity.marineId);
      //小孩每日评价列表
      this.queryChildComment();
    } else {
      this.queryActImageList(null, Activity.id);
      this.queryActVideoList(null, Activity.id);
    }
    this.contentTaskView();
    //课程参与统计
    this.queryCourseSignCount();
    //家长期待列表
    this.queryChildGrowthExpect();
  },

  contentTaskView() {
    WxParse.wxParse('contentTaskHtml', 'html', util.base64.decode(this.data.Activity.contentTask), this, 5);
  },
  queryActivityInfo: function(activityId) {
    var that = this;
    // 查询小孩参与的活动信息
    wx.request({
      url: app.httpUrl + '/activity/queryActInfo',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityId: activityId
      },
      success: (res) => {
        if (res.data.code == '000') {
          var Activity = res.data.data;
          Activity.courseId = Activity.productId;
          Activity.activityId = Activity.id;
          that.loadData(Activity);
        }
      }
    })
  },
  queryChildActInfo: function(activityId, childId) {
    var that = this;
    // 查询小孩参与的活动信息
    wx.request({
      url: app.httpUrl + '/activity/queryChildActInfo',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityId: activityId,
        childId: childId
      },
      success: (res) => {
        if (res.data.code == '000') {
          var data = res.data.data;
          data.startDate = util.formatDate(data.startDate, 'Y年M月D日');
          data.endDate = util.formatDate(data.endDate, 'Y年M月D日');
          that.setData({
            ChildActInfo: data
          });
          this.queryActImageList(data.marineId, activityId);
          this.queryActVideoList(data.marineId, activityId);
        }
      }
    })
  },
  queryCourseImgList: function(courseId) {
    let that = this;
    wx.request({
      url: app.httpUrl + '/course/queryCourseImgList',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        courseId: courseId
      },
      success: (res) => {
        var urls = [],
          courseImg = null;
        var imgList = res.data.data;
        for (var i in imgList) {
          urls.push(app.imgUrl + imgList[i].imgUrl);
        }
        var currTime = new Date().getTime();
        var currDate, currDay;
        if (currTime > that.data.Activity.endDate) {
          currDay = imgList.length;
        } else {
          currDay = parseInt(Math.ceil((currTime - that.data.Activity.startDate) / 1000 / 60 / 60 / 24));
          if (currDay > imgList.length) {
            currDay = imgList.length;
          }
        }
        if (currDay < 0) currDay = 1;
        that.setData({
          courseImgList: urls,
          courseImg: urls.length > 0 ? urls[currDay - 1] : null,
          currDay: currDay - 1
        })
      }
    })
  },
  queryMarineMember: function(marineId) {
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/queryMarMemList/' + marineId,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        that.setData({
          memberlist: res.data.data
        })
      }
    })
  },
  queryActVideoList: function(marineId, activityId) {
    // 视频
    let that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryListByPage',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        marineId: marineId,
        activityId: activityId,
        page: 1,
        rows: 3,
        liveType: "video"
      },
      method: "POST",
      success: (res) => {
        var list = res.data.data.results;
        for (var i in list) {
          for (var j in list[i].attachList) {
            if (j == 0) {
              list[i].firstVideoUrl = app.imgUrl + list[i].attachList[j].attachUrl;
              list[i].firstThumbUrl = app.imgUrl + list[i].attachList[j].thumbAttachUrl;
            }
          }
        }
        that.setData({
          videolist: list
        })
      }
    })
  },
  // queryActImageList: function(marineId, activityId) {
  //   // 活动图片
  //   let that = this;
  //   wx.request({
  //     url: app.httpUrl + '/activity/live/queryListByPage',
  //     header: {
  //       'xcx-xtoken': app.globalData.openid,
  //       'content-type': 'application/json' // 默认值
  //     },
  //     data: {
  //       marineId: marineId,
  //       activityId: activityId,
  //       page: 1,
  //       rows: 6,
  //       liveType: "image",
  //     },
  //     method: "POST",
  //     success: (res) => {
  //       var list = res.data.data.results;
  //       for (var i in list) {
  //         for (var j in list[i].attachList) {
  //           if (j == 0) {
  //             list[i].firstImg = app.imgUrl + list[i].attachList[j].attachUrl;
  //           }
  //           list[i].attachList[j].attachUrl = app.imgUrl + list[i].attachList[j].attachUrl;
  //         }
  //       }
  //       that.setData({
  //         imagelist: list
  //       })
  //     }
  //   })
  // },
  queryActImageList: function(marineId, activityId) {
    // 活动图片
    let that = this;
    if (!marineId) {
      marineId = null
    }
    wx.request({
      // url: app.httpUrl + '/activity/live/queryListForImgByPage',
      url: app.httpUrl + '/activity/live/queryListForImgByPage',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        marineId: marineId,
        activityId: activityId,
        page: 1,
        rows: 6,
        msgType: "image",
      },
      method: "POST",
      success: (res) => {
        var list = res.data.data.results;
        that.setData({
          imagelist: list
        })
      }
    })
  },
  queryChildComment: function() {
    let that = this
    // 首页头部地区接口
    wx.request({
      url: app.httpUrl + '/activity/tutor/queryChildComment',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityChildId: this.data.Activity.activityChildId
      },
      success: res => {
        if (res.data.code == '000') {
          var list = res.data.data;
          var currTime = new Date().getTime();
          for (var i in list) {
            list[i].keyList = list[i].keywords.split(",");
            var commentDate = list[i].commentDate;
            var commentTime = commentDate.replace(/(.{4})(.*)/, "$1-$2").replace(/(.{7})(.*)/, "$1-$2");
            var totalDay = parseInt(Math.ceil((new Date(commentTime) - that.data.Activity.startDate) / 1000 / 60 / 60 / 24)) + 1;
            list[i].day = "Day" + totalDay;
          }
          that.setData({
            commentList: list
          })
        }
      }
    })
  },
  queryCourseSignCount: function() {
    let that = this
    // 首页头部地区接口
    wx.request({
      url: app.httpUrl + '/course/queryCourseSignCount/' + this.data.Activity.courseId,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: res => {
        that.setData({
          courseSignCount: res.data
        })
      }
    })
  },
  queryExpect: function() {
    let that = this
    // 首页头部地区接口
    wx.request({
      url: app.httpUrl + '/activity/live/queryExpect',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityId: this.data.Activity.activityId,
        activityChildId: this.data.Activity.activityChildId
      },
      success: res => {
        if (res.data.code == '000') {
          that.setData({
            expectInfo: res.data.data
          })
        }
      }
    })
  },
  queryChildGrowthExpect: function() {
    var that = this;
    wx.request({
      url: app.httpUrl + '/activity/live/queryChildGrowthExpect',
      data: {
        activityId: this.data.Activity.activityId,
        page: 1,
        rows: 3
      },
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success: function(res) {
        var list = res.data.data.results;
        var expectList = [];
        for (var i in list) {
          list[i].createDate = util.formatDate(list[i].createTime, 'Y.M.D h:m');
          var relation = '';
          if (list[i].childRelation == 1) relation = "宝贝的爸爸";
          else if (list[i].childRelation == 2) relation = "宝贝的妈妈";
          else if (list[i].childRelation == 3) relation = "宝贝的亲戚";
          else relation = "宝贝父母的朋友";
          list[i].parentDesc = list[i].childName + relation;
          expectList.push(list[i]);
        }
        that.setData({
          expectList: expectList
        });
      }
    })
  },
  childMoreTab: function() {
    this.setData({
      isShowAllChild: this.data.isShowAllChild ? false : true
    })
  },
  marinePreviewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = [src];
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表     
    })
  },
  previewImageCourse: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: this.data.courseImgList // 需要预览的图片http链接列表     
    })
  },
  memberPreviewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var list = [];
    for (var i in this.data.memberlist) {
      list[i] = app.imgUrl + this.data.memberlist[i].childImg;
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表     
    })
  },
  // 图片
  seephoto: function(e) {
    let src = e.currentTarget.dataset.url;
    let list = this.data.imagelist;
    let arr = [];
    for (let a = 0; a < list.length; a++) {
      arr.push('http://img.xue110.top/taoxuequ' + list[a].sysUrl)
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: arr // 需要预览的图片http链接列表     
    })
  },
  // 图片预览
  previewImage: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var idx = event.currentTarget.dataset.idx;
    var id = event.currentTarget.dataset.id;
    var list = this.data.imagelist[idx].attachList;
    var urls = [];
    for (var i in list) {
      urls.push(list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
    this.addClicks(id);
  },
  previewImageExpect: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var idx = event.currentTarget.dataset.idx;
    var list = this.data.expectList[idx].attachList;
    var urls = [];
    for (var i in list) {
      urls.push(app.imgUrl + list[i].attachUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: urls // 需要预览的图片http链接列表     
    })
  },
  inputValue: '',
  data: {
    src: '',
    bindInputBlur: function(e) {
      this.inputValue = e.detail.value
    },
    bindButtonTap: function() {
      var that = this
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: ['front', 'back'],
        success: function(res) {
          that.setData({
            src: res.tempFilePath
          })
        }
      })
    }
  },
  queryHeadBanner: function() {
    wx.request({
      url: app.httpUrl + '/home/queryHeadBanner',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        this.setData({
          slides: res.data.data - 20
        })
      }
    })
  },
  addClicks: function(id) {
    wx.request({
      url: app.httpUrl + '/activity/live/addClicks',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        id: id
      },
      success: (res) => {}
    })
  },
  swiperChange: function(e) {
    this.setData({
      currDay: e.detail.current
    })
  },
  addchild: function() {
    this.setData({
      showModalStatus: true //让模态框显示
    });
  },
  bindPickerChange_relation: function(e) {
    var relation_index = this.data.relation_index;
    var childRelation = e.detail.value;
    for (var i in this.data.relation) {
      if (this.data.relation[i].value == childRelation) {
        relation_index = i;
        break;
      }
    }
    this.setData({
      childRelation: e.detail.value,
      relation_index: relation_index
    })
  },
  formReset: function() {
    this.setData({
      childName: '',
      parentMobile: '',
      relation_index: '0',
      childRelation: '',
      showModalStatus: false //让模态框显示
    })
  },
  // form表单
  formSubmit: function(e) {
    var childName = e.detail.value.childName;
    if (childName == '') {
      wx.showToast({
        title: '宝贝姓名不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    var parentMobile = e.detail.value.parentMobile;
    if (parentMobile == '') {
      wx.showToast({
        title: '家长报名电话不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    var code = e.detail.value.code;
    if (code == '') {
      wx.showToast({
        title: '验证码不能为空',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!(this.data.childRelation && parseInt(this.data.childRelation) > 0)) {
      wx.showToast({
        title: '请选择您和宝贝的关系哦！',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    wx.request({
      url: app.httpUrl + '/user/addParentUser',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        activityId: this.data.Activity.activityId,
        childName: childName,
        parentMobile: parentMobile,
        childRelation: this.data.childRelation,
        code: code
      },
      success: (res) => {
        if (res.data.code != '000') {
          var msg = res.data.code == '1026' && res.data.data != null ? '请用您提供给我们的手机号码绑定：' + res.data.data : res.data.msg;
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 5000
          });
        } else {
          wx.showToast({
            title: '绑定成功',
            icon: 'success',
            duration: 3000
          });
          this.setData({
            childName: '',
            parentMobile: '',
            childRelation: '',
            relation_index: '0',
            showModalStatus: false //让模态框显示
          })
          this.initPage();
        }
      }
    })
  },
  parentMobileInput: function(e) {
    this.setData({
      parentMobile: e.detail.value
    })
  },
  /**
   * 跳转更多
   */
  jump: function(e) {
    let id = e.currentTarget.dataset.id;
    let activeId = e.currentTarget.dataset.activityid;
    let marineId = e.currentTarget.dataset.marineid;
    marineId = !marineId ? '' : marineId;
    let activityChildId = e.currentTarget.dataset.activityChildId;
    if (id == 0) { //图片跳转
      wx.navigateTo({
        url: '/pages/MoreImage/MoreImage?activityId=' + activeId + '&marineId=' + marineId,
      })
    } else if (id == 1) { //现场视频
      wx.navigateTo({
        url: '/pages/MoreVideo/MoreVideo?activityId=' + activeId + '&marineId=' + marineId,
      })
    } else if (id == 2) { //学生评价
      wx.navigateTo({
        url: '/pages/babyFile/babyFile?activityId=' + activeId + '&marineId=' + marineId,
      })
    } else if (id == 3) { //家长评价
      wx.navigateTo({
        url: '/pages/expectList/expectList?activityId=' + activeId,
      })
    } else {

    }

  },
  sendValidCode: function() {
    var that = this;
    var parentMobile = that.data.parentMobile;
    if (!(parentMobile && parentMobile.length == 11)) {
      wx.showToast({
        title: '请正确输入手机号！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({
      timer: setInterval(function() {
        var wait = 0;
        if (that.data.wait >= 0) {
          wait = that.data.wait + 1;
        }
        that.setData({
          wait: wait,
          isCodeActive: 60 - wait > 0 ? true : false,
          codeActiveText: "重新获取" + (60 - wait) + "s"
        })
      }, 1000)
    })
    wx.request({
      url: app.httpUrl + '/user/sendSms',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      data: {
        parentMobile: parentMobile
      },
      success: (res) => {
        if (res.data.code != '000') {
          wx.showToast({
            title: '验证码发送失败！',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }
    })
  },
  //右上角分享功能  
  onShareAppMessage: function(res) {
    let that = this;
    return {
      title: '',
      path: 'pages/study/study?activeId=' + app.globalData.activityId + '&childId=' + app.globalData.childId
    }
  },
})